<!-- templates/upload.html -->
{% extends "base.html" %}

{% block title %}Garbage-识别{% endblock %}

{% block page_content %}
<div>
    <div id="alert-container"></div>
    <div class="upload-box">
        <h3>上传图片</h3>
        <form method="post" enctype="multipart/form-data" class="form-custom" id="custom-form">
            <input style="display: none;" type="file" name="file" class="form-control" id="inputGroupFile04" aria-describedby="inputGroupFileAddon04" aria-label="Upload" accept="image/*">
            <br>
            <div id="preview" class="mt-3" >
                <img style="width: 200px;" src="{{ url_for("static", filename="default_pic.png") }}" alt="请选择图片"/>
            </div>
            <br>
            <div class="text-center">
                <button type="button" id="photo-btn" class="btn btn-primary">拍照上传</button>
                <button type="submit" id="submit" class="btn btn-primary">开始识别</button>
            </div>
        </form>
    </div>
    <!-- 在模板中添加摄像头容器 -->
    <div id="cameraModal" class="modal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">拍照</h5>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
          </div>
          <div class="modal-body">
            <video id="cameraStream" autoplay playsinline></video>
            <canvas id="captureCanvas" style="display:none;"></canvas>
          </div>
          <div class="modal-footer">
            <button id="cancelBtn" data-dismiss="modal" class="btn btn-primary">取消</button>
            <button id="captureBtn" class="btn btn-primary">拍照</button>
            <button id="confirmBtn" class="btn btn-success" style="display:none;">确认</button>
          </div>
        </div>
      </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
    {{ super() }}

    <script>
        // 获取 DOM 元素
        const fileInput = document.getElementById('inputGroupFile04');
        const previewContainer = document.getElementById('preview');

        // 当点击预览区域时，触发文件选择框
        previewContainer.addEventListener('click', function () {
            fileInput.click(); // 触发文件选择框
        });

        // 文件选择后的处理逻辑
        document.getElementById('inputGroupFile04').addEventListener('change', function (event) {
          const file = event.target.files[0]; // 获取上传的文件
          const previewContainer = document.getElementById('preview');

          // 清空之前的预览内容
          previewContainer.innerHTML = '';

          if (file && file.type.startsWith('image/')) {
            const img = document.createElement('img');
            img.src = URL.createObjectURL(file); // 创建图片的临时 URL
            img.style.maxWidth = '100%'; // 设置图片的最大宽度
            img.classList.add('img-fluid'); // 使用 Bootstrap 的响应式图片类

            // 将图片添加到预览容器中
            previewContainer.appendChild(img);

          } else {
            // 如果没有选择有效的图片文件，显示提示文字
            previewContainer.textContent = '点击此处选择图片';
            showAlert('请上传有效的图片文件！');
          }
        });

        function showAlert(message) {
            document.getElementById('alert-container').innerHTML = `<div id="customAlert" class="alert alert-danger" role="alert" style="display: block;">
                <span id="alertMessage">${message}</span>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
            </div>`;
        }

        document.getElementById('custom-form').addEventListener('submit', function (event) {
            const fileInput = document.getElementById('inputGroupFile04');
            const file = fileInput.files[0];

            // 自定义验证：检查文件是否存在且为图片
            if (!file || !file.type.startsWith('image/')) {
                event.preventDefault(); // 阻止表单提交
                showAlert('图片不可为空！');
            }

            // 自定义验证：检查文件大小是否超过限制（例如 5MB）
            if (file && file.size > 5 * 1024 * 1024) {
                event.preventDefault(); // 阻止表单提交
                showAlert('文件大小不能超过 5MB！');
            }
        });
  </script>
    <script>// 新增摄像头相关逻辑
        document.getElementById("photo-btn").addEventListener('click', async () => {
          try {
            const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
            const cameraStream = document.getElementById('cameraStream');
            cameraStream.srcObject = stream;

            // 显示摄像头模态框
            $('#cameraModal').modal('show');

            // 拍照按钮点击事件
            document.getElementById('captureBtn').addEventListener('click', () => {
              const canvas = document.getElementById('captureCanvas');
              const context = canvas.getContext('2d');
              canvas.width = cameraStream.videoWidth;
              canvas.height = cameraStream.videoHeight;
              context.drawImage(cameraStream, 0, 0);

              // 显示确认按钮
              document.getElementById('confirmBtn').style.display = 'inline-block';
            });

            // 确认按钮点击事件
            document.getElementById('confirmBtn').addEventListener('click', () => {
              const canvas = document.getElementById('captureCanvas');
              canvas.toBlob(blob => {
                // 获取当前时间戳并格式化为短字符串
                const timestamp = Date.now(); // 时间戳（毫秒）
                const fileName = `photo_${timestamp}.jpg`; // 文件名加上时间戳
                const file = new File([blob], fileName, { type: "image/jpeg" });

                // 模拟文件选择
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(file);
                fileInput.files = dataTransfer.files;

                // 触发change事件
                const event = new Event('change', { bubbles: true });
                fileInput.dispatchEvent(event);

                // 关闭模态框
                $('#cameraModal').modal('hide');
                stream.getTracks().forEach(track => track.stop());
              }, 'image/jpeg', 0.8);
            });

          } catch (error) {
            showAlert('无法访问摄像头，请检查权限设置');
          }
        });
    </script>
{% endblock %}